<?php

namespace app\common\service;

use app\common\model\User as UserModel;
use app\common\model\Wxapp as WxappModel;
use app\common\model\Setting as SettingModel;
use app\common\model\dealer\Setting as DealerSettingModel;
use app\common\library\wechat\WxTplMsg;
use app\common\library\sms\Driver as SmsDriver;

/**
 * 消息通知服务
 * Class Message
 * @package app\common\service
 */
class Message
{
    /**
     * 订单支付成功后通知
     * @param \think\Model $order
     * @param int $orderType 订单类型 (10商城订单)
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function payment($order, $orderType = 10)
    {
        // 1. 微信模板消息
        $template = SettingModel::getItem('tplMsg', $order['wxapp_id'])['payment'];
        if (!$template['is_enable'] || empty($template['template_id'])) {
            return false;
        }

        // 页面链接
        $urls = [
            10 => 'pages/order/detail',
        ];
        // 发送模板消息
        $status = $this->sendTemplateMessage($order['wxapp_id'], [
            'touser' => $order['user']['open_id'],
            'template_id' => $template['template_id'],
            //'page' => $urls[$orderType] . '?order_id=' . $order['order_id'],
            'page' => 'pages/index/index',
            //'form_id' => $formId['form_id'],
            'data' => [
                'first' => '购买的商品已支付成功，请留意物流信息哦！么么哒！~~',
                //订单编号
                'keyword1' => $order['order_no'],
                //商品名称
                'keyword2' => $this->formatGoodsName($order['goods']),
                //订单总价
                'keyword3' => $order['pay_price'],
                //订单状态
                'keyword4' => '支付成功',
                //下单时间
                'keyword5' => date('Y-m-d H:i:s', $order['pay_time']),
                // 商品名称
                'remark' => '如您需要帮助，请联系客服'
            ]
        ]);
        // 标记formid已使用
        //$status === true && FormIdService::setIsUsed($formId['id']);
        // 2. 商家短信通知
        //$smsConfig = SettingModel::getItem('sms', $order['wxapp_id']);
        //$SmsDriver = new SmsDriver($smsConfig);
        //return $SmsDriver->sendSms('order_pay', ['order_no' => $order['order_no']]);

        return $status;
    }

    /**
     * 后台发货通知
     * @param \think\Model $order
     * @param int $orderType 订单类型 (10商城订单)
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function delivery($order, $orderType = 10)
    {
        // 微信模板消息
        $template = SettingModel::getItem('tplMsg', $order['wxapp_id'])['delivery'];
        if (!$template['is_enable'] || empty($template['template_id'])) {
            return false;
        }
        // 获取可用的formid
        //if (!$formId = FormIdService::getAvailableFormId($order['user_id'])) {
        //    return false;
        //}
        // 页面链接
        $urls = [
            10 => 'pages/my_order/pages/order/detail/index',
            20 => 'pages/points_mall/pages/order_details/index'
        ];
        // 发送模板消息
        $status = $this->sendTemplateMessage($order['wxapp_id'], [
            'touser' => $order['user']['open_id'],
            'template_id' => $template['template_id'],
            'page' => $urls[$orderType] . '?order_id=' . $order['order_id'],
            'data' => [
                //说明
                'first' => '您购买的订单已经发货啦，正快马加鞭向您飞奔而去。',
                //订单编号
                'keyword1' => $order['order_no'],
                //发货时间
                'keyword2' => date('Y-m-d H:i:s', $order['delivery_time']),
                //物流公司
                'keyword3' => $order['express']['express_name'],
                //快递单号
                'keyword4' => $order['express_no'],
                //收件信息
                'keyword5' => $order['address']['name'] . implode('', $order['address']['region']) . $order['address']['detail'],
                //备注
                'remark' => '请保持收件手机畅通！'
            ]
        ]);
        return $status;
    }

    /**
     * 分销商提现审核通知
     * @param \app\common\model\dealer\Withdraw $withdraw
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function withdraw($withdraw)
    {
        // 模板消息id
        $template = DealerSettingModel::getItem('template_msg', $withdraw['wxapp_id']);
        if (empty($template['withdraw_tpl'])) {
            return false;
        }
        // 获取可用的formid
        //if (!$formId = FormIdService::getAvailableFormId($withdraw['user_id'])) {
        //    return false;
        //}
        // 获取用户信息
        $user = UserModel::detail($withdraw['user_id']);
        // 发送模板消息
        $remark = '有任何疑问，请联系客服';

        if ($withdraw['apply_status'] == 30) {
            $remark = $withdraw['reject_reason'];
        }
        $status = $this->sendTemplateMessage($withdraw['wxapp_id'], [
            'touser' => $user['open_id'],
            'template_id' => $template['withdraw_tpl'],
            'page' => 'pages/index/index',
            //'page' => 'pages/dealer/withdraw/list/list',
            //'form_id' => $formId['form_id'],
            'data' => [
                'first' => '您好。您的提现申请已处理!',
                //提现金额
                'keyword1' => $withdraw['money'],
                //提现方式
                'keyword2' =>  $withdraw['pay_type']['text'],
                // 提现时间
                'keyword3' => $withdraw['create_time'],
                //提现状态
                'keyword4' =>  $withdraw->applyStatus[$withdraw['apply_status']],
                //审核时间
                'keyword5' => date('Y-m-d H:i:s'),
                // 备注
                'remark' => $remark,
            ]
        ]);
        // 标记formid已使用
        //FormIdService::setIsUsed($formId['id']);
        return $status;
    }

    /**
     * 发送模板消息
     * @param $wxappId
     * @param $params
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    private function sendTemplateMessage($wxappId, $params)
    {
        // 微信模板消息
        $wxConfig = WxappModel::getWxappCache($wxappId);
        $WxTplMsg = new WxTplMsg($wxConfig['app_id'], $wxConfig['app_secret']);
        return $WxTplMsg->sendTemplateMessage($params);
    }

    /**
     * 格式化商品名称
     * @param $goodsData
     * @return string
     */
    private function formatGoodsName($goodsData)
    {
        $str = '';
        foreach ($goodsData as $goods) {
            $str .= $goods['goods_name'] . ' ';
        }
        return $str;
    }

}